package com.innover.controller;

import com.innover.domain.FileInfo;
import com.innover.domain.UserRecord;
import com.innover.domain.WeeklyVersion;
import com.innover.service.FileInfoService;
import com.innover.service.UserRecordService;
import com.innover.service.WeeklyVersionService;
import com.innover.util.AppFolders;
import com.innover.util.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 12-7-18
 * Time: 下午3:12
 * To change this template use File | Settings | File Templates.
 */
@Controller
public class APIController {
    Logger LOGGER = LoggerFactory.getLogger("APIController");

    @Autowired
    @Qualifier("fileInfoService")
    private FileInfoService fileInfoService;

    @Autowired
    @Qualifier("weeklyVersionService")
    private WeeklyVersionService weeklyVersionService;

    @Autowired
    @Qualifier("userRecordService")
    private UserRecordService userRecordService;
    @RequestMapping("/uploadtest")
    public String uploadTest(){
        return "upload_page_test";
    }

    @RequestMapping("/uploadrecord")
    public ModelAndView upload(@RequestParam("recordfile") CommonsMultipartFile recordfile, @RequestParam("deviceId") String deviceId,  @RequestParam("ass_song") String ass_song, HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("defaultJsonView");
        if (null != recordfile) {
            System.out.println("myFile:" + recordfile.toString());
            String path = request.getSession().getServletContext().getRealPath(AppFolders.UPLOAD_RECORD_FOLDER+"/" + deviceId + "/"); // 获取本地存储路径// WebUtils.getRealPath(servletContext,"/"+user.getUsername()+"/"); //
            File folder = new File(path);
            if (!folder.exists()) {
                folder.mkdirs();
            }
            String fileSuffix = FileUtil.getFileSuffix(recordfile.getFileItem().getName());
            String filenameInDB = UUID.randomUUID().toString().replace("-", "") + "_" + System.currentTimeMillis() + fileSuffix;
            File file = new File(path, filenameInDB); // 新建一个文件
            try {
                recordfile.getFileItem().write(file); // 将上传的文件写入新建的文件中
                //将文件信息存入数据库中
                UserRecord userRecord = new UserRecord();
                userRecord.setDeviceId(deviceId);
                userRecord.setRecordName(recordfile.getFileItem().getName());
                userRecord.setRecordPath(file.getAbsolutePath());
                userRecord.setAssSong(ass_song);
                userRecord.setUploadDate(new Date());
                System.out.println(userRecord.toString());
                LOGGER.info(userRecord.toString());
                userRecordService.editSave(userRecord);
                UserRecord temp = userRecordService.queryByRecordPath(filenameInDB);
                //下面将链接拼装一下
                String uri = request.getRequestURI();
                String url = request.getRequestURL().toString();
                url = url.replace(uri, "/download") + "?id=" + temp.getId();
                Map<String,String> myUrl=new HashMap<String,String>();
                myUrl.put("shareLink",url);
                mav.addObject(myUrl);
                return mav;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @RequestMapping("/getinfo")
    public ModelAndView getinfo(@RequestParam("id") int id) {
        ModelAndView mav = new ModelAndView("defaultJsonView");
        UserRecord userRecord = userRecordService.get(UserRecord.class, id);
        mav.addObject(userRecord);
        return mav;
    }

    /**
     * 根据id查找文件路径并下载文件
     *
     * @param id
     * @param scope    （两种标志作为判断：record/song）
     * @param request
     * @param response
     */
    @RequestMapping("/download")
    public void download(@RequestParam("id") int id, @RequestParam("scope") String scope, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("UTF-8");
        java.io.BufferedInputStream bis = null;
        java.io.BufferedOutputStream bos = null;
        String downLoadPath=null;
        String fileName=null;
        if("song".equals(scope)){
            FileInfo fileInfo = fileInfoService.get(FileInfo.class, id);
            downLoadPath = fileInfo.getFilePath();
            fileName = fileInfo.getFileName();
        }else if("record".equals(scope)){
            UserRecord userRecord=userRecordService.get(UserRecord.class,id);
            downLoadPath=userRecord.getRecordPath();
            fileName=userRecord.getRecordName();
        }
        try {
            long fileLength = new File(downLoadPath).length();
            response.setContentType("application/x-msdownload;");
            response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
            response.setHeader("Content-Length", String.valueOf(fileLength));
            bis = new BufferedInputStream(new FileInputStream(downLoadPath));
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
        }

    }

    /**
     * 将服务器端的文件列表传递到手机客户端
     *
     * @param update （两种标志作为判断：init/weekly）
     * @return
     */
    @RequestMapping("/getList")
    public ModelAndView getList(@RequestParam("update") String update) {
        ModelAndView mav = new ModelAndView("defaultJsonView");
        String hql = " from FileInfo f ";
        List list = null;
        if ("init".equals(update)) {
            hql += "where f.weekly=0";
            list = fileInfoService.queryAll(hql);
            mav.addObject(list);
        }
        if ("weekly".equals(update)) {
            hql += "where f.weekly=1";
            list = fileInfoService.queryAll(hql);
            mav.addObject(list);
        }
        return mav;
    }

    @RequestMapping("/getWeekInfo")
    public ModelAndView getWeekInfo(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("defaultJsonView");
        List list = weeklyVersionService.queryAll(" from WeeklyVersion");
        if (null != list && list.size() > 0) {
            WeeklyVersion weeklyVersion = (WeeklyVersion) list.get(0);
            mav.addObject(weeklyVersion);
        }
        return mav;
    }
}
